<template>
  <el-text><h3>借阅记录</h3></el-text>
  <el-divider />
  <div>
    <el-table
      :data="recordList"
      style="width: 100%"
      :row-class-name="tableRowClassName"
    >
      <el-table-column type="index" label="序号" width="80" />
      <el-table-column prop="b_name" label="图书名称" width="200" />
      <el-table-column prop="c_name" label="图书类别" />
      <el-table-column prop="start_time" label="开始时间" />
      <el-table-column prop="end_time" label="结束时间" />
      <el-table-column label="剩余归天数">
        <template #default="scope">
          <span v-if="scope.row.r_state == 0">
            <el-tag :type="scope.row.sub_num <= 5 ? 'danger' : 'success'">
              {{ scope.row.sub_num }} 天</el-tag>
          </span>
        </template>
      </el-table-column>
      <el-table-column label="状态" width="100">
        <template #default="scope">
          <el-text v-if="scope.row.r_state == 0" type="danger">
            未归还
          </el-text>
          <el-text v-else type="success"> 已归还 </el-text>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="180">
        <template #default="scope">
          <el-button type="primary" size="small">详情</el-button>
          &nbsp;
          <el-button-group v-if="scope.row.r_state == 0">
            <el-button
              type="warning"
              size="small"
              @click="book_revert(scope.row.record_id, scope.row.b_name)"
              >归还</el-button
            >
            <el-button type="danger" size="small">编辑</el-button>
          </el-button-group>
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>

<script setup>
import { onMounted, ref } from "vue";
import http from "../axios";
import { ElMessage, ElMessageBox } from "element-plus";

const tableRowClassName = ({ row, rowIndex }) => {
  if (row.r_state == 0 && row.sub_num <= 5) {
    return "danger-row";
  }
  return "";
};

const recordList = ref([]);
onMounted(() => {
  record_list();
});

const record_list = () => {
  http.get("/record/list").then((resp) => {
    console.log(resp);
    recordList.value = resp.data.data.list;
  });
};

const book_revert = (id, name) => {
  ElMessageBox.confirm(
    `确认归还 <strong>《${name}》</strong> 图书吗?`,
    "温馨提示",
    { dangerouslyUseHTMLString: true }
  ).then(() => {
    http.put("/record/update", { recordId: id }).then((resp) => {
      if (resp.data.code != "200") {
        ElMessage.error(resp.data.message);
        return;
      }
      ElMessage.success(resp.data.message);
      record_list();
    });
  });
};
</script>

<style>
.el-table .danger-row {
  --el-table-tr-bg-color: rgba(200, 100, 100, 0.5);
}
</style>
